import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  BadRequestException,
} from '@nestjs/common';
import { Logger } from '@nestjs/common/services/logger.service';
import BusinessErroror from 'libs/common/utils/BusinessError';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(GlobalExceptionFilter.name);

  catch(exception: Error, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    let  message = 
    exception?.message || 
   ( Array.isArray((exception as any)?.response?.message) ?
    (
      (exception as any)?.response?.message.join &&
      (exception as any)?.response?.message?.join(',') 
    )
    : (exception as any)?.response?.message
    ) || 'Internal server error'
    
    console.log('<<<<<<<<<<<<<');
    this.logger.error(new Date());
    this.logger.error(request.url);
    this.logger.error(message);
    console.log('>>>>>>>>>>>>>>');

    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    if (exception instanceof HttpException) {
      status = exception.getStatus();
      if (exception instanceof BadRequestException) {
        status = exception.getStatus();
      }
    } else if (exception instanceof BusinessErroror) {
      status = exception.code;
    }
    response.status(HttpStatus.OK).json({
      code: status,
      timestamp: new Date(),
      path: request.url,
      message,
    });
  }
}
